package wh.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wh.bos.dao.base.AreaRepository;
import wh.bos.dao.base.FixdeAreaRepository;
import wh.bos.dao.take_delivery.OrderRepository;
import wh.bos.dao.take_delivery.WorkBillRepository;
import wh.bos.domain.base.Area;
import wh.bos.domain.base.Courier;
import wh.bos.domain.base.FixedArea;
import wh.bos.domain.base.SubArea;
import wh.bos.domain.take_delivery.Constants;
import wh.bos.domain.take_delivery.Order;
import wh.bos.domain.take_delivery.WorkBill;
import wh.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService{

	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private FixdeAreaRepository fixdeAreaRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	
	@Override
	public void saveOrder(Order order) {
		order.setOrderNum(UUID.randomUUID().toString()); // 设置订单号
		order.setOrderTime(new Date());// 设置下单时间
		//寄件人
		Area sendArea = order.getSendArea();
		Area area = areaRepository.findByProvinceAndCityAndDistrict
		(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
		// 收件人 省市区
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository
				.findByProvinceAndCityAndDistrict(recArea.getProvince(),
				recArea.getCity(), recArea.getDistrict());
		order.setSendArea(area);
		order.setRecArea(persistRecArea);
		
		//自动分单,基于CRM地址库中的地址,获取定区,关联快递员
		String fixedAreaId = WebClient.create
		(Constants.CRM_MANAGEMENT_HOST+"/services/customerService/findFixedAreaIdByCustomerId/"+order.getCustomer_id())
		.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			FixedArea fixedArea = fixdeAreaRepository.findOne(fixedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()){
				Courier courier = iterator.next();
				if (courier != null) {
					//自动分单成功
					saveOrder(order, courier);
					generateWorkBill(order);
					System.out.println("分单完成");
					return;
				}
			}
		}
		
		//自动分单,通过省市区,以及分区关键字,匹配地址,基于分区关联快递员
	
		for(SubArea subArea : area.getSubareas() ){
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						saveOrder(order, courier);
						generateWorkBill(order);
						System.out.println("分单完成");
						return;
					}
				}
			}
		}
		//手工分单
		order.setOrderType("2");
		orderRepository.save(order);
	}
	//生成工单,发送短信
	private void generateWorkBill(Order order) {
		//生成新工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillRepository.save(workBill);
		
		//发送短信(假)
		System.out.println("短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
		+ ",联系人:" + order.getSendName() + ",手机:"
		+ order.getSendMobile() + "，快递员捎话："
		+ order.getSendMobileMsg());
		
		// 修改工单状态
				workBill.setPickstate("已通知");
	}
	//分单成功后,调用orderRepository保存订单
	public void saveOrder(Order order, Courier courier) {
		order.setOrderType("1");
		order.setCourier(courier);
		order.setOrderNum(UUID.randomUUID().toString());
		orderRepository.save(order);
	}

}
